package com.ywu.boot.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Objects;

/**
 * @ClassName TraceLogFilter
 * @Description TODO
 * @Author GroundDemo
 * @Date 2024/3/16 12:20
 * @Version 1.0
 **/
@Slf4j
public class TraceLogInterceptor implements HandlerInterceptor {
    private static final ThreadLocal<Long> currentStartTime = new ThreadLocal<>();

    // 前置拦截
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        StringBuffer requestURL = request.getRequestURL();
        String method = request.getMethod();
        String traceId = request.getHeader("X-Pix-Ywu-Trace-Id");
        String spanId = request.getHeader("X-Pix-Ywu-Span-Id");
        Date date = new Date();
        long time = date.getTime();
        currentStartTime.set(time);
        // 打印日志
        log.info("[trace begin] [{}] [{}] traceId: {}, spanId: {}", method, requestURL, traceId, spanId);
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        StringBuffer requestURL = request.getRequestURL();
        String method = request.getMethod();
        String traceId = request.getHeader("X-Pix-Ywu-Trace-Id");
        String spanId = request.getHeader("X-Pix-Ywu-Span-Id");
        Date date = new Date();
        long time = date.getTime();
        Long startTime = currentStartTime.get();
        long costTime = 0L;
        if (Objects.nonNull(startTime)) {
            costTime = time - startTime;
        }
        // 打印日志
        log.info("[trace end] [{}] [{}] traceId: {}, spanId: {}, const time {}", method, requestURL, traceId, spanId, costTime);
    }
}
